//
//  VNExpress.m
//  VietNews
//
//  Created by Nguyen .a.Hph on 7/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "VNExpress.h"
#import "VietNewsArticleViewController.h"
#import "Util.h"

@implementation VNExpress
+(void)getPostContent:(NSString *)url site:(Element *)site viewController:(UIViewController *)controller{
    NSLog(@"VNExpress getPostContent");
    //load more comment if button visible
    UIWebView *webViewDetail = (UIWebView *)[controller.view viewWithTag:1000];
    UIWebView *webViewHidden = (UIWebView *)[controller.view viewWithTag:1001];
    NSString *moreCommentBtn = [webViewHidden stringByEvaluatingJavaScriptFromString:@"$('#divOutPaging').attr('style')"];
    if (moreCommentBtn.length==0)
        return;
    NSRange range = [moreCommentBtn rangeOfString:@"display: none"];
    if (range.location!=NSNotFound)
        return;
    [webViewHidden stringByEvaluatingJavaScriptFromString:@"$('#comment_viewctn_bottom').click()"];
    dispatch_queue_t jsExecute = dispatch_queue_create("jsExecuter",NULL);
    dispatch_async(jsExecute, ^{
        [NSThread sleepForTimeInterval:5];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *html = [webViewHidden stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
            NSError *error;
            GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithHTMLString:html options:0 error:&error];
            if (error)
                NSLog(@"%@",error);
            if (doc==nil)
                return;
            
            //store currentScroll position
            [[NSUserDefaults standardUserDefaults] setInteger:
             [[webViewDetail stringByEvaluatingJavaScriptFromString: @"scrollY"]
              intValue] forKey: @"currentScroll"];
            
            [XHTMLParser parseArticleDetailBy:doc url:url site:site viewController:controller];
        });
    });
    dispatch_release(jsExecute);
}

+(NSString *)getNextSectionUrl:(GDataXMLDocument *)doc{
    NSString *nextXPath = @"//div[@class='continue']/a/@href";
    @try {
        NSArray *arr = [doc nodesForXPath:nextXPath error:nil];
        if ([arr count]>0)
        {
            NSString *href = [[arr objectAtIndex:0] stringValue];
            href = [href substringBetween:@"('" st2:@"')"];
            href = [[NSString stringWithFormat:@"default.asp?d=%@",href] lowercaseString];
            return href;
        }
    }
    @catch (NSException *exception) {
        NSLog(@"%s: %@",__FUNCTION__,exception);
    }
    @finally {
        
    }
    return @"";
}
@end
